package v;

import c.GridTableController;
import core.constructor.constructor;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import m.JXTableModel;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.decorator.Highlighter;
import org.jdesktop.swingx.decorator.HighlighterFactory;
import tools.Util;

public class SeleccionadorIU extends javax.swing.JDialog {
    
    private JXTable dev_tabla;
    private DefaultTableModel modeloT;
    private Map<String, String> datosSelect = new HashMap<String, String>();
    private Object Object_clase;
    private String urlClase;
    private String metodo;
    
    public SeleccionadorIU(String sqlTabla, String titulosColumas, constructor c, String urlClase, String metodo) {
        super(c, true);
        initComponents();
        
        setUrlClase(urlClase);
        setMetodo(metodo);
        tabla = setTabla(tabla, sqlTabla, titulosColumas, c);
        GridTableController.setFilterStatic(cBuscar, tabla);
        setSize(new Dimension(800, 400));
//        setResizable(false);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cBuscar = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabla = new org.jdesktop.swingx.JXTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        cBuscar.setFont(new java.awt.Font("Tahoma", 0, 14));
        cBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cBuscarActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel1.setText("Buscar");

        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tabla);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(13, 13, 13)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cBuscarActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cBuscarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SeleccionadorIU.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SeleccionadorIU.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SeleccionadorIU.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SeleccionadorIU.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                new SeleccionadorIU().setVisible(true);
//            }
//        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField cBuscar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.swingx.JXTable tabla;
    // End of variables declaration//GEN-END:variables

    public Object[] datosTabla(String... values) {
        
        Util u = new Util();
        
        Object[] dataGrid = new Object[2];
        
        values[0] = values[0];
        
        dataGrid[0] = values[0].trim().split(",");
        dataGrid[1] = u.sqlDatos(values[1]);
        
        return dataGrid;
    }
    
    public JXTable setTabla(JXTable tablaImplementacion, String sqlTabla, String titulosColumas, constructor c) {
        dev_tabla = tablaImplementacion;
        modeloT = new DefaultTableModel();
        
        JXTableModel t = new JXTableModel();

        //Enviar Primero los titulos y luego la SQL
        setModeloTabla(datosTabla(titulosColumas, sqlTabla), c);

        //dev_tabla = autoResizeColWidth(dev_tabla, modeloT);
        return dev_tabla;
    }

    /**
     * Asigna un Modelo a la Tabla
     * y trae de la Clase Consultar Munucipios
     * Los vectores que tendra la JTable.
     */
    public void setModeloTabla(Object[] ed_RegistrosTabla, constructor c) {

        //BVerTodos.setVisible(mostrar);

        //Se instancia el Modelo de la Tabla
        DefaultTableModel ed_modeloTabla = new DefaultTableModel();

        //Se instancia la Clase que hara la logica de la Consulta
        //Clientes cliente = new Clientes();

        Object[] ed_datosVector = ed_RegistrosTabla;
        
        
        
        ed_modeloTabla.setDataVector((Object[][]) ed_datosVector[1], (Object[]) ed_datosVector[0]);

        //Se Aplica el Modelo a la Tabla
        dev_tabla.setModel(ed_modeloTabla);

        //Alto de las Filas
        dev_tabla.setRowHeight(24);

        // Permitir solo una seleccion por vez
        dev_tabla.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        // Bloquear columnas
        dev_tabla.getTableHeader().setReorderingAllowed(false);



        //Hacer Que tabla se tenga ordenamiento. http://chuwiki.chuidiang.org/index.php?title=JTable:_Ordenar_y_filtrar_filas
        // Instanciamos el TableRowSorter y lo añadimos al JTable
        TableRowSorter<TableModel> columOrdenamiento = new TableRowSorter<TableModel>(ed_modeloTabla);
        dev_tabla.setRowSorter(columOrdenamiento);
        
        
        dev_tabla.setAutoCreateRowSorter(true);

        //TableColumn columna = dev_tabla.getColumn("Codigo");

        //columna.setPreferredWidth(70);


        //Desactivar el AutoResize para que tome un Ancho definido
        dev_tabla.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);


        /**
        Eliminar una columna de la tabla(ocultar) pero visible para el modelo
         * ed_Tabla.removeColumn(ed_Tabla.getColumn("Eliminar"));
         **/
        //Asignarle botones para Compactar Contenido
        dev_tabla.setColumnControlVisible(true);


        //Distingir Registros por Color 
        Highlighter simpleStriping = HighlighterFactory.createSimpleStriping();
        dev_tabla.setHighlighters(simpleStriping);






        //Centrar Titulos de Tabla
        ((DefaultTableCellRenderer) dev_tabla.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(
                SwingConstants.CENTER);


        //Hacer por Defecto tome el tamaño de la Tabla.
        dev_tabla.setHorizontalScrollEnabled(true);
        dev_tabla.packAll();
        
        dev_tabla.addMouseListener(new MouseAdapter() {
            
            public void mouseClicked(MouseEvent e) {
                
                int nColumnas = dev_tabla.getColumnCount();
                
                int fila = dev_tabla.rowAtPoint(e.getPoint()); // columnas = tabla.columnAtPoint(e.getPoint())
                if (fila > -1) {
//            cedula = String.valueOf(Tabla_Empleados.getValueAt(fila,0));

                    
                    
                    
                    for (int i = 0; i < nColumnas; i++) {
//                        System.out.println("String.valueOf(Tabla_Empleados.getValueAt(fila," + i + "))" + String.valueOf(dev_tabla.getValueAt(fila, i)));
//                        System.out.print(" " + dev_tabla.getColumnModel().getColumn(i).getHeaderValue().toString());

                        datosSelect.put(dev_tabla.getColumnModel().getColumn(i).getHeaderValue().toString(), String.valueOf(dev_tabla.getValueAt(fila, i)));
                    }


                    //cargar(getUrlClase(), getMetodo());
                    cerrar();



//                    System.out.println("String.valueOf(Tabla_Empleados.getValueAt(fila,0))" + String.valueOf(dev_tabla.getValueAt(fila,0)));
//                    System.out.println("String.valueOf(Tabla_Empleados.getValueAt(fila,1))" + String.valueOf(dev_tabla.getValueAt(fila,1)));
//                    System.out.println("String.valueOf(Tabla_Empleados.getValueAt(fila,2))" + String.valueOf(dev_tabla.getValueAt(fila,2)));


//            ventana();
                }
                
                
                
            }
        });
        
        
        modeloT = ed_modeloTabla;
        
        
        
    }
    
    void cargarDatos(String urlClase) {
        try {
            Class c = Object_clase.getClass();
            String cn = c.toString();
            
            Class c2 = Class.forName(cn);
            
            
            c2.getMethod("cargar");
            
        } catch (NoSuchMethodException ex) {
            Logger.getLogger(SeleccionadorIU.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
            Logger.getLogger(SeleccionadorIU.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(SeleccionadorIU.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
        
    }
    
    private void cerrar() {
        this.setVisible(false);
    }
    
    void cargar(String urlClase, String metodo) {
        System.out.println("urlClase = " + urlClase);
        
        Class clase;
        Object objeto;
        
        Method metodoCarga; //Este es el Metodo que se cargara Dinamicamente y se ejecutara o-o
        Class[] tipoParametros;
        Object[] valorParametros;
        
        
        try {
            // Cargamos la clase
            clase = Class.forName(urlClase);

            // Instanciamos un objeto de la clase
            try {
                objeto = clase.newInstance();
                
                try {

                    // Accedemos al metodo n, con un parametro (java.util.HashMap)
                    tipoParametros = new Class[1];
                    tipoParametros[0] = Class.forName("java.util.HashMap");
                    metodoCarga = clase.getMethod(metodo, tipoParametros);
                    valorParametros = new Object[1];
                    valorParametros[0] = datosSelect;
                    metodoCarga.invoke(objeto, valorParametros);
                    System.out.println("Ejecutando Conversion Dinamica() ...");
                    
                    
                } catch (NoSuchMethodException e) {
                    System.out.println("Error al acceder al metodo. " + e);
                } catch (SecurityException e) {
                    System.out.println("Error al acceder al metodo. " + e);
                } catch (InvocationTargetException e) {
                    System.out.println("Error al ejecutar el metodo. " + e);
                }
                
            } catch (InstantiationException e) {
                System.out.println("Error al instanciar el objeto. :( " + e.getMessage());
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                System.out.println("Error al instanciar el objeto. " + e);
            }
            
        } catch (ClassNotFoundException e) {
            System.out.println("No se ha encontrado la clase. " + e);
        }
    }
    
    public String getMetodo() {
        return metodo;
    }
    
    public void setMetodo(String metodo) {
        this.metodo = metodo;
    }
    
    public String getUrlClase() {
        return urlClase;
    }
    
    public void setUrlClase(String urlClase) {
        this.urlClase = urlClase;
    }
    
    public Map<String, String> getDatosSelect() {
        return datosSelect;
    }
}
